<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="礼包名称" prop="packName">
        <el-input v-model.trim="queryParams.packName" placeholder="请输入礼包名称" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市标签" prop="cityName">
        <el-select
          v-model="queryParams.cityName"
          @change="handleSearch(true)"
          fit-input-width
          placeholder="请选择"
        >
          <el-option
            v-for="item in cityNameOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          v-hasPermi="['marketing:virtualGiftPack:add']"
          icon="Plus"
          @click="handleAdd()"
          >新增</el-button
        >
      </el-col>
      <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList">
      <el-table-column label="礼包名称" align="center" prop="packName" width="240">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleSkip(row)">{{ row.packName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="城市标签" align="center" prop="cityName" />
      <el-table-column label="销售价格" align="center" prop="price" />
      <el-table-column label="售卖库存数量" align="center" prop="packNum" />
      <el-table-column label="可售库存" align="center" prop="currentStock" />
      <el-table-column label="已售卖（订单完成）" align="center" prop="soldQuantity" width="160" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <el-button :type="row.status == 1 ? 'success' : ''" link>
            {{ statusOptions.find((item) => item.value === row?.status)?.label }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tagId">
        <template #default="{ row }">
          {{ tagComboList?.find((item) => item.tagId === row.tagId)?.tagName }}
        </template>
      </el-table-column>
      <el-table-column label="小程序礼包排序" align="center" prop="sort" />

      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" fixed="right" min-width="200">
        <template #default="{ row }">
          <el-button
            v-hasPermi="['marketing:virtualGiftPack:onshelf']"
            link
            :disabled="handleDisabled(row)"
            type="primary"
            @click="handleListed(row)"
            >{{ row.status === 0 || row.status === 2 ? '上架' : '下架' }}</el-button
          >
          <el-button
            v-hasPermi="['marketing:virtualGiftPack:edit']"
            link
            type="primary"
            v-show="row.status === 0 || row.status === 2"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-hasPermi="['marketing:virtualGiftPack:delete']"
            link
            type="primary"
            :disabled="row.status !== 0 && row.status !== 2"
            @click="handleDelete(row)"
            >删除</el-button
          >
          <el-button
            v-hasPermi="['marketing:virtualGiftPack:details']"
            link
            type="primary"
            @click="handleDetails(row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList()"
    />
    <dialogDetails ref="dialogRef" :dialogTitle="dialogTitle" @closeDialog="getList()" />
  </div>
</template>
<script setup>
import {
  getGiftPackSalesListApi,
  topGiftPackSalesApi,
  bottomGiftPackSalesApi,
  editGiftPackSalesApi
} from '@/api/marketing/virtualGiftPack'
import dialogDetails from './components/details'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => {
  return globalStore.myCityList
})

const showSearch = ref(true)
const loading = ref(false)
const total = ref(0)
const tableList = ref([])
const queryParams = ref({
  packName: null,
  status: '',
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0]
})
const statusOptions = [
  {
    label: '待上架',
    value: 0
  },
  {
    label: '上架中',
    value: 1
  },
  {
    label: '已下架',
    value: 2
  },
  {
    label: '上架中-已售罄',
    value: 3
  }
]
const queryRef = ref()
const dialogTitle = ref()
const dialogRef = ref()
function handleSearch(type) {
  if (type) {
    // 搜索
    queryParams.value.pageNum = 1
    getList()
  } else {
    // 重置
    queryRef.value.resetFields()
    queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
    console.log('queryParams.cityName', queryParams.cityName)
    handleSearch(true)
  }
}
import { getTagComboList } from '@/api/meal/comboTag'
import { parseTime } from '@/utils/tools'
const tagComboList = ref([])
/**获取标签数据 */
function getTagCombo() {
  getTagComboList({
    pageNum: 1,
    pageSize: 9999,
    enable: 1,
    cityName: queryParams.value.cityName
  }).then((res) => {
    console.log(res)
    tagComboList.value = res.rows || []
  })
}
function handleAdd() {
  dialogTitle.value = '新增'
  setTimeout(() => {
    dialogRef.value.init({ cityName: queryParams.value.cityName })
  }, 50)
}
/**上下架 */
function handleListed(row) {
  if (row.status === 0 || row.status === 2) {
    ElMessageBox.confirm(`确认要上架${row.packName}吗?`, '系统提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      center: false
    }).then(() => {
      topGiftPackSalesApi(row.id).then((res) => {
        console.log('上架', res)
        getList()
      })
    })
  } else {
    ElMessageBox.confirm(`确认要下架${row.packName}吗?`, '系统提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      center: false
    }).then(() => {
      bottomGiftPackSalesApi(row.id).then((res) => {
        console.log('下架', res)
        getList()
      })
    })
  }
}
function handleDisabled(row) {
  if (row.status === 0 || row.status === 2) {
    return row.packNum - row.soldQuantity <= 0
  } else {
    return false
  }
}
function handleEdit(row) {
  dialogTitle.value = '编辑'

  setTimeout(() => {
    dialogRef.value.init(row)
  }, 50)
}

const router = useRouter()
/**跳转礼包列表 */
function handleSkip(row) {
  router.push({
    path: '/market/giftPack',
    query: { id: row.couponPackId, packName: row.packName, cityName: row.cityName }
  })
}
function handleDelete(row) {
  ElMessageBox.confirm(`确认要删除${row.packName}吗?`, '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  }).then(() => {
    const params = { id: row.id, status: -1, couponPackId: row.couponPackId }
    editGiftPackSalesApi(params).then((res) => {
      console.log('删除', res)
      getList()
    })
  })
}
function handleDetails(row) {
  dialogTitle.value = '详情'
  setTimeout(() => {
    dialogRef.value.init(row)
  }, 50)
}
function getList() {
  loading.value = true
  getGiftPackSalesListApi(queryParams.value)
    .then((res) => {
      loading.value = false
      tableList.value = res?.data?.rows.map((item) => {
        return {
          ...item,
          createTime: item.createTime && parseTime(item.createTime)
        }
      })
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
    })
}
onMounted(() => {
  getTagCombo()
  getList()
})
</script>
<style lang="scss" scoped></style>
